package com.wanmait.translate.configuration.configuration;

import com.wanmait.translate.configuration.other.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {
    @Bean
    //创建shirofilter，负责拦截所有请求
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //过滤器中注入管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        Map<String,String> map=new HashMap<>();
        //authc为一种过滤器的简称，表示这个资源需要认证和授权,
        //map.put("/index.jsp","authc");
        //可以使用通配符，**表示除了登陆页面所有的都拦截
        //map.put("/**","authc");
        map.put("/**","anon");
        //对登陆的路径放行
        map.put("/login","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置拦截请求要跳转的页面，默认为login.jsp
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        return shiroFilterFactoryBean;
    }
    @Bean
    //创建安全管理器
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        //管理器中注入数据源
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }
    @Bean
    @Primary
    //创建自定义Realm
    public Realm getRealm(){
        MyRealm myRealm = new MyRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        myRealm.setCredentialsMatcher(credentialsMatcher);

        //设置缓存实现为EhCacheManager
        myRealm.setCacheManager(new EhCacheManager());
        //开启全局缓存
        myRealm.setCachingEnabled(true);
        //开启认证缓存
        myRealm.setAuthenticationCachingEnabled(true);
        //设置认证的缓存名(可选，有默认值)
        myRealm.setAuthenticationCacheName("AuthenticationCache");
        //开启授权缓存
        myRealm.setAuthorizationCachingEnabled(true);
        //设置授权的缓存名(可选，有默认值)
        myRealm.setAuthorizationCacheName("AuthorizationCache");
        return myRealm;
    }
}
